import React from 'react';
import { Select, Input, Button, message } from 'antd';
import { StyledDiv } from './styled';
import { DrawIndex, TimesOfWin } from './utils';
let currentAthlete = DrawIndex;

export const Badminton = () => {
  const [athletes, setAthletes] = React.useState<string[]>([]);
  const [value, setValue] = React.useState<string>("");
  const [draws, setDraws] = React.useState<{ [key: string]: string }[]>([]);
  const [times, setTimes] = React.useState<{ [key: string]: string }[]>([]);
  const [project, setProject] = React.useState<string>("1");
  const womanRef = React.useRef(null);

  const onAdd = () => {
    if (!athletes.includes(value) && value !== "") {
      //@ts-ignore
      const woman = womanRef && womanRef.current?.state?.value;
      if (project === '5' && !woman) {
        message.warn('同时输入一个男运动员和一个女运动员！')
        return;
      }
      athletes.push(value);
      if (woman) {
        athletes.push(woman);
        //@ts-ignore
        womanRef.current.state.value = '';
      }
      setAthletes([...athletes]);
      setValue("");
      currentAthlete = DrawIndex.slice(0, athletes.length);
    }
  }

  const onDraw = (athlete: string) => {
    if (draws[athlete]) {
      message.error('不可重复抽签！！！')
      return;
    }
    const index = Math.floor(Math.random() * currentAthlete.length);
    draws[athlete] = currentAthlete[index];
    currentAthlete.splice(index, 1);


    for (let i = 0; i < 3; i++) {
      const time = Math.floor(Math.random() * 3);
      if (i === 0) {
        times[athlete] = TimesOfWin[time];
      } else {
        times[athlete] += (`${i !== 0 ? ', ' : ''}${TimesOfWin[time]}`);
      }

    }
    setDraws({ ...draws });
    setTimes({ ...times });
  }

  const onGroup = () => {
    setDraws([]);
    setTimes([]);

    athletes.forEach((athlete, i) => {
      while (true) {
        const index = Math.floor(Math.random() * currentAthlete.length);
        const g = currentAthlete[index];
        if (project === '5') {
          if (Object.keys(draws).some((dr, _i) => {
            if (_i % 2 === i % 2) {
              return draws[dr].replace(/\d/g, '') === g.replace(/\d/g, '');
            }
            return false;
          })) {
            continue;
          }
        }
        if (Object.keys(draws).every(dr => draws[dr] !== g)) {
          draws[athlete] = g;
          break;
        }
      }
    });
    setDraws({ ...draws });
  }

  const resetDraw = (e: string) => {
    setAthletes([]);
    setValue('');
    setDraws([]);
    setTimes([]);
    setProject(e)
  }

  return (
    <StyledDiv project-a={project}>
      <div className="title">羽毛球抽签</div>
      <div className="header">
        <div className="common project">
          <label>项目</label>
          <Select defaultValue="1" value={project} onChange={resetDraw}>
            <Select.Option value="1">男单</Select.Option>
            <Select.Option value="2">女单</Select.Option>
            <Select.Option value="3">男双</Select.Option>
            <Select.Option value="4">女双</Select.Option>
            <Select.Option value="5">混双</Select.Option>
          </Select>
        </div>
        <div className="athlete">
          <div className="common">
            <label>人员</label>
            <Input value={value} placeholder={project === '5' ? '输入男运动员姓名' : '输入运动员姓名'} onChange={e => setValue(e.target.value)} />
            {project === '5' && <Input ref={womanRef} placeholder={'输入女运动员姓名'} />}
          </div>
          <Button onClick={onAdd} disabled={Object.keys(draws).length > 0} type="primary">添加</Button>
          {
            ['3', '4', '5'].includes(project)
            && <Button onClick={onGroup} disabled={Object.keys(draws).length > 0} style={{ right: '-196px' }} type="primary">分组</Button>
          }
        </div>
      </div>
      <div className="draw-list">
        {
          athletes.map(athlete => {
            return (
              <div key={athlete} className="draw">
                <Button onClick={() => onDraw(athlete)}>{athlete}</Button>
                <Input value={`${draws[athlete] || ''} ${times[athlete] ? `: (${times[athlete] || ''})` : ''}`} disabled />
              </div>
            );
          })
        }
      </div>
    </StyledDiv>
  );
}